#!/bin/bash
CUR_PATH=$(dirname $(readlink -f "$0"))
TOP_DIR=${CUR_PATH}/../
SHA256_TOOL=${TOP_DIR}"/scripts/gen_security_check.sh"
PACKAGE_PATH=$1
REPACK_NAME="Ascend310-driver-repack-aarch64-minirc.tar.gz"

USR_CFG_DIR=${TOP_DIR}/repack
OUT_DIR=${TOP_DIR}/output/repack
WORK_DIR=${OUT_DIR}/driver
FOLDER_NAME="driver"

show_help()
{
	echo "Usage:"
	printf "%-60s\n" "	$0 <src package path>"
	printf "%-60s %-30s\n" "	$0 ../Ascend310-driver-xxx-aarch64-minirc.tar.gz"
	exit 1
}

gen_sha256()
{
	if [ -e ${OUT_DIR}/check_sha.sh ];then
		rm -f ${OUT_DIR}/check_sha.sh
	fi

	cd ${OUT_DIR}
	
	${SHA256_TOOL} ${OUT_DIR} ${FOLDER_NAME} sha256 >/dev/null 2>&1
	if [ $? -ne 0 ];then
		echo "Failed: gen sha256 failed!"
		return 1
	fi
	cd - >/dev/null 2>&1
}

check_para()
{
	if [ ! -f ${FOLDER_PATH} ];then
		echo "Failed: ${FOLDER_PATH} is not exist, please check!"
		show_help
	fi

	if [ ! -d ${OUT_DIR} ];then
		mkdir -p ${OUT_DIR}
	fi

	if [ -d ${WORK_DIR} ];then
		rm -rf ${WORK_DIR}
	fi
}

unpack()
{
	tar -xzf ${PACKAGE_PATH} -C ${OUT_DIR}
	if [ $? -ne 0 ];then
		echo "Failed: tar failed!"
		exit 1
	fi
}

repack()
{
	cd ${OUT_DIR}
	tar -zcf ${REPACK_NAME} ${FOLDER_NAME}
	if [ $? -ne 0 ];then
		echo "Failed: repack failed!"
		exit 1
	fi
}

copy_user_cfg()
{
	cp -rdpf ${USR_CFG_DIR}/* ${WORK_DIR}
}

if [ $# -ne 1 ];then
	show_help
fi

check_para
unpack
copy_user_cfg
gen_sha256
repack

echo "repack success!"
exit 0
